<?php
/**
 * Created by PhpStorm.
 * User: xutao
 * Date: 2018/8/6
 * Time: 18:00
 */
namespace app\common\model;
use app\admin\model\MemberModel;
use think\Db;
use think\Model;
use think\Session;

class TravelsModel extends Model{
    protected $table = 'think_travels';
    protected $autoWriteTimestamp = 'datetime';
    //
    //用户
    public function getMemberIdAttr($value){
        if($value){
            $re = MemberModel::get($value);
            if($re){
                return ['id'=>$re->id,'nickname'=>$re->nickname];
            }else{
                return [];
            }

        }else{
            return [];
        }
    }
    //序列化存储地址address
    public function setAddressAttr($value){
        return serialize($value);
    }
    //查询时反序列化
    public function getAddressAttr($value){
        return unserialize($value);
    }
    public function getTravelModelAttr($value){
        $data = [
            1=>'自由行',
            2=>'半自由行及跟团游'
        ];
        return $data[$value];
    }
    public function getRelationshipAttr($value){
        $data = [
            1=>'朋友',
            2=>'父母',
            3=>'配偶',
            4=>'子女'
        ];
        return $data[$value];
    }
    //获取准备篇图片地址
    public function getPreparationImgAttr($value){
        if($value){
            $img = explode(',',$value);
            $re = ImgModel::where('id','in',$img)->select();
            return $re;
        }else{
            return [];
        }
    }
    //获取 正式篇
    public function getTravelRecordsIdAttr($value){
        if($value){
            $tr_ids = explode(',',$value);
            $re = TrModel::where('id','in',$tr_ids)->order('date asc')->select();
            return $re;
        }else{
            return [];
        }
    }
    //获取详细信息id
    public function getInfoIdAttr($value){
        if($value){
            $re = InfoModel::get($value);
            return $re;
        }else{
            return [];
        }
    }
    //删除
    public static function del($id){

        // 启动事务
        Db::startTrans();
        try{
            $re = TravelsModel::get($id);
            $del_img = [];//删除的图片ids
            $del_travel_records_id=[];//旅行日记id
            $del_recommend_id = [];//推荐ids
            $del_accommodation_id = [];//住宿ids
            //详细信息id
            $del_info_id = null;
            //详细信息
           // echo "==========================详细信息====================<br>";
            if($re->info_id){
                $info = $re->info_id;
                $del_info_id = $info->id;
                //==========================住宿信息====================<br>";
                foreach ($info->accommodation_id as $k=>$v){
                    $del_accommodation_id[] = $v->id;
                }
                foreach ($info->recommend_id as $k=>$v){
                    $del_recommend_id[] = $v->id;
                }
            }
           // echo "==========================旅行记录====================<br>";
            if($re->travel_records_id){

                foreach ($re->travel_records_id as $k=>$v){
                    $del_travel_records_id[] = $v->id;
                    if($v->img){
                        foreach ($v->img as $k1=>$v1){
                            //删除图片
//                            if(file_exists(ROOT_PATH.$v1['src'])){
//                                unlink(ROOT_PATH.$v1['src']);
//                            }
                            $del_img[] = $v1->id;
                        }
                    }
                }
            }
            //删除的图片ids
            if($del_img){
                Db::table('think_img')->delete($del_img);
            }
            //旅行日记id
            if($del_travel_records_id){
                Db::table('think_travel_records')->delete($del_travel_records_id);
            }
            //推荐ids
            if($del_recommend_id){
                Db::table('think_recommend')->delete($del_recommend_id);
            }
            //住宿ids
            if($del_accommodation_id){
                Db::table('think_accommodation')->delete($del_accommodation_id);
            }
            //详细信息
            if($del_info_id){
                Db::table('think_info')->delete($del_info_id);
            }
            //删除游记
            Db::table('think_travels')->delete($id);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }
    //添加游记
    public static function add($data){
        // 启动事务
         Db::startTrans();
         try {
            //游记主表
            $travels = [
                'member_id' => Session::get('member')['id'],
                'cover_src' => $data['cover_src']?$data['cover_src']:"",
                'title' => $data['title']?$data['title']:'',
                'start_date' => $data['start_date']?$data['start_date']:null,
                'end_date' => $data['end_date']?$data['end_date']:null,
                'travel_model' => $data['travel_model']?$data['travel_model']:null,
                'relationship' => $data['relationship']?$data['relationship']:'',
                'start_message' => $data['start_message']?$data['start_message']:'',
                'end_message' => $data['end_message']?$data['end_message']:'',
                'address' => $data['address']
            ];

            //准备篇图片
            if ($data['preparation_img']) {
                $preparation_img_ids = [];
                foreach ($data['preparation_img'] as $k => $v) {
                    $m = new ImgModel();
                    $m->allowField(true)->save($v);
                    $preparation_img_ids[] = $m->id;
                }
                $travels['preparation_img'] = implode(',', $preparation_img_ids);
            }

            //正式篇
            $travel_records = [];
            $data_travel_records = $data['travel_records'];
            if ($data_travel_records) {
                foreach ($data_travel_records as $k => $v) {
                   
                    if ($v['img']) {
                        //组合正式篇的图片id
                        $img_ids = [];
                        foreach ($v['img'] as $k1 => $v1) {
                            $imgmodel  = new ImgModel();
                             $imgmodel->allowField(true)->save($v1);
                            $img_ids[] = $imgmodel->id;
                        }
                        $v['img'] = implode(',', $img_ids);
                    }
                    // unset($v['img']);
                    $travel_records[] = $v;
                }
            }

            //正式篇写入数据库
            if ($travel_records) {
                $tr_ids = [];
                foreach ($travel_records as $k => $v) {
                    $trmodel = new TrModel();
                    $trmodel->allowField(true)->save($v);
//                    $tr = TrModel::create($v);
                    $tr_ids[] = $trmodel->id;
                }
                $travels['travel_records_id'] = implode(',', $tr_ids);
            }

            //详细信息
            $info = $data['info'];
            //住宿
            if ($info['accommodation']) {
                $a_ids = [];
                foreach ($info['accommodation'] as $k => $v) {
                    $ac = new Accommodation();
                    $ac->allowField(true)->save($v);

                    $a_ids[] = $ac->id;
                }
                $info['accommodation_id'] = implode(',', $a_ids);
                unset($info['accommodation']);
            }

            //推荐
            if ($info['recommend']) {
                $r_ids = [];
                foreach ($info['recommend'] as $k => $v) {
                    $recommend = new Recommend();
                    $recommend->allowField(true)->save($v);
                    $r_ids[] = $recommend->id;
                }
                $info['recommend_id'] = implode(',', $r_ids);
                unset($info['recommend']);
            }

            //详细信息写入数据库
            if ($info) {
                $travel_info = new InfoModel();
                $travel_info->allowField(true)->data($info);
                $travel_info->save();
                $travels['info_id'] = $travel_info->id;
            }

            //游记主表写入
             $travelsmodel = new TravelsModel();
             $travelsmodel->allowField(true)->save($travels);

            // 提交事务
             Db::commit();
             return true;
         } catch (\Exception $e) {
             // 回滚事务
             Db::rollback();
             return false;
         }
    }

    public static function edit($data){

        // 启动事务
        Db::startTrans();
        try {
        $re = Db::table('think_travels')->field('create_time')->find($data['id']);
        //删除之间的数据
        self::del($data['id']);
            //游记主表
            $travels = [
                'id'=>$data['id'],
                'member_id' => Session::get('member')['id'],
                'cover_src' => $data['cover_src']?$data['cover_src']:"",
                'title' => $data['title']?$data['title']:'',
                'start_date' => $data['start_date']?$data['start_date']:null,
                'end_date' => $data['end_date']?$data['end_date']:null,
                'travel_model' => $data['travel_model']?$data['travel_model']:null,
                'relationship' => $data['relationship']?$data['relationship']:'',
                'start_message' => $data['start_message']?$data['start_message']:'',
                'end_message' => $data['end_message']?$data['end_message']:'',
                'create_time'=>$re['create_time'],  // 提取之前数据的创建时间
                'address' => $data['address']
            ];
            //准备篇图片
            if ($data['preparation_img']) {
                $preparation_img_ids = [];
                foreach ($data['preparation_img'] as $k => $v) {
                    $m = new ImgModel();
                    $m->allowField(true)->save($v);
                    $preparation_img_ids[] = $m->id;
                }
                $travels['preparation_img'] = implode(',', $preparation_img_ids);
            }
            //正式篇
            $travel_records = [];
            $data_travel_records = $data['travel_records'];
            if ($data_travel_records) {
                foreach ($data_travel_records as $k => $v) {
                    if ($v['img']) {
                        //组合正式篇的图片id
                        $img_ids = [];
                        foreach ($v['img'] as $k1 => $v1) {
                            $imgmodel  = new ImgModel();
                            $imgmodel->allowField(true)->save($v1);
                            $img_ids[] = $imgmodel->id;
                        }

                        $v['img'] = implode(',', $img_ids);
                    }
                    // unset($v['img']);
                    $travel_records[] = $v;
                }
            }
            //正式篇写入数据库
            if ($travel_records) {
                $tr_ids = [];
                foreach ($travel_records as $k => $v) {
                    $trmodel = new TrModel();
                    $trmodel->allowField(true)->save($v);
//                    $tr = TrModel::create($v);
                    $tr_ids[] = $trmodel->id;
                }
                $travels['travel_records_id'] = implode(',', $tr_ids);
            }
            //详细信息
            $info = $data['info'];
            //住宿
            if ($info['accommodation']) {
                $a_ids = [];
                foreach ($info['accommodation'] as $k => $v) {
                    $ac = new Accommodation();
                    $ac->allowField(true)->save($v);
                    $a_ids[] = $ac->id;
                }
                $info['accommodation_id'] = implode(',', $a_ids);
                unset($info['accommodation']);
            }
            //推荐
            if ($info['recommend']) {
                $r_ids = [];
                foreach ($info['recommend'] as $k => $v) {
                    $recommend = new Recommend();
                    $recommend->allowField(true)->save($v);
                    $r_ids[] = $recommend->id;
                }
                $info['recommend_id'] = implode(',', $r_ids);
                unset($info['recommend']);
            }
            //详细信息写入数据库
            if ($info) {
                $travel_info = new InfoModel();
                $travel_info->allowField(true)->data($info);
                $travel_info->save();
                $travels['info_id'] = $travel_info->id;
            }
            //游记主表写入
            $travelsmodel = new TravelsModel();
            $travelsmodel->allowField(true)->save($travels);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }
}